/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.contentprovider.webprovider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 *
 * @author Kenneth
 */
public class GoogleContentProvider {

    /**
     *
     * @param term
     * @return a species-related image-URL that can be found using a given term.
     * This is the most relevant hit according to Google.
     * @throws MalformedURLException
     */
    public static String getImageURLFromGoogle(String term) throws MalformedURLException {
        String imageUrl = "";
        try {
            String urlAsString = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=species%20" + term.replace(" ", "%20");
            InputStream is;
            URL url = new URL(urlAsString);
            URLConnection connection = url.openConnection();
            is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            try {
                String element;
                while ((element = br.readLine()) != null) {
                    String[] split = element.split("\"unescapedUrl\":\"");
                    imageUrl = split[1].substring(0, split[1].indexOf("\",\""));
                    if ((!imageUrl.isEmpty()) && (imageUrl.length() > 1)) {
                        break;
                    }
                }
            } catch (IOException localThrowable1) {
                throw localThrowable1;
            }
        } catch (IOException ex) {
            Logger.getLogger(UniprotContentProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return imageUrl;
    }

    /**
     *
     * @param term a term to search for
     * @param amount of images to be retained
     * @return a species-related image-URL that can be found using a given term.
     * This is the most relevant hit according to Google.
     * @throws MalformedURLException
     */
    public static List<String> getImageURLsFromGoogle(String term, int amount) throws MalformedURLException {
        List<String> images = new ArrayList<>();
        try {
            String urlAsString = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=species%20" + term.replace(" ", "%20");
            InputStream is;
            URL url = new URL(urlAsString);
            URLConnection connection = url.openConnection();
            is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            try {
                String element;
                while ((element = br.readLine()) != null) {
                    String[] split = element.split("\"unescapedUrl\":\"");
                    String imageUrl = split[1].substring(0, split[1].indexOf("\",\""));
                    if ((!imageUrl.isEmpty()) && (imageUrl.length() > 1)) {
                        images.add(imageUrl);
                    }
                    if (images.size() > amount) {
                        break;
                    }
                }
            } catch (IOException localThrowable1) {
                throw localThrowable1;
            }
        } catch (IOException ex) {
            Logger.getLogger(UniprotContentProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return images;
    }

    /**
     *
     * @param term term to search for
     * @param amount of images to retain
     * @return a list of images that can be freely distributed (even commercially). This is searched with google's licence filter
     * @throws MalformedURLException
     * @throws IOException
     */
    public static List<String> getFreelyDistributableImageURLsFromGoogle(String term, int amount) throws MalformedURLException, IOException {
        List<String> images = new ArrayList<>();
        String urlAsString = ""
                + "http://www.google.com/search?as_st=y&tbm=isch&as_q=taxonomy%20" + term.replace(" ", "%20") + "&as_epq=&as_oq=&as_eq=&cr=&as_sitesearch=&safe=images&tbs=sur:fmc";
        Document doc = Jsoup.connect(urlAsString).userAgent("Mozilla").get();
        // get page title
        Elements imageElements = doc.select("img");
        for (org.jsoup.nodes.Element aTopList : imageElements) {
            images.add(aTopList.attr("src"));
        }
        return images;
    }

}
